package com.zg.third.qcc.utils;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.util.HexUtil;
import cn.hutool.crypto.SmUtil;
import cn.hutool.crypto.asymmetric.SM2;
import cn.hutool.crypto.symmetric.SM4;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import org.bouncycastle.asn1.ASN1EncodableVector;
import org.bouncycastle.asn1.ASN1Integer;
import org.bouncycastle.asn1.ASN1Sequence;
import org.bouncycastle.asn1.DERSequence;
import org.bouncycastle.jcajce.spec.SM2ParameterSpec;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.pqc.math.linearalgebra.ByteUtils;
import org.bouncycastle.util.encoders.Hex;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.io.IOException;
import java.math.BigInteger;
import java.nio.charset.StandardCharsets;
import java.security.*;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Arrays;
import java.util.Map;
import java.util.TreeMap;

/**
 * 本系统加解密工具
 * 使用SM3withSM2进行签名验签
 * 使用SM4进行全报文加解密
 * 业务方使用规范：
 * 1.向系统申请appId，需要将业务方的SM2公钥上传到系统方，同时系统方会给申请方发放系统方的SM2公钥及SM4秘钥
 * 2.业务方在发送请求时使用SM3withSM2对报文进行签名，并将签名连同报文进行SM4加密后传输给系统方
 * 3.系统方收到请求后使用SM4解密报文，并使用SM3withSM2对报文进行验签
 * 4.系统方返回响应时使用SM3withSM2对报文进行签名，并将签名连同报文进行SM4加密后传输给业务方
 * 5.业务方收到响应后使用SM4解密报文，并使用SM3withSM2对报文进行验签
 * 签名串：{@link SysEncryptionUtil#sortField(Map)}
 * 签名：{@link SysEncryptionUtil#sign(String, String, String)}
 * 验签：{@link SysEncryptionUtil#verifySign(String, String, String, String)}
 * 加密：{@link SysEncryptionUtil#encryptEcb(String, String)}
 * 解密：{@link SysEncryptionUtil#decryptEcb(String, String)}
 * 密钥对：{@link SysEncryptionUtil#sm2KeyGen()}
 * 对称秘钥：{@link SysEncryptionUtil#sm4KeyGen()}
 */
@Slf4j
public class SysEncryptionUtil {

    static{
        Security.addProvider(new BouncyCastleProvider());
    }
    //================SM2相关属性=====================
    //算法常量:SM3withSM2
    public static final String ALGORITHM_SM3SM2_BCPROV = "SM3withSM2";
    private final static int SM3withSM2_RS_LEN=32;
    //================SM4相关属性=====================
    private static final String ENCODING = "UTF-8";
    public static final String ALGORITHM_NAME = "SM4";
    // 加密算法/分组加密模式/分组填充方式
    // PKCS5Padding-以8个字节为一组进行分组加密
    // 定义分组加密模式使用：PKCS5Padding
    public static final String ALGORITHM_NAME_ECB_PADDING = "SM4/ECB/PKCS5Padding";
    // 128-32位16进制；256-64位16进制
    public static final int DEFAULT_KEY_SIZE = 128;
    //SM2密钥对生成工具
    public static void sm2KeyGen() {
        // 创建sm2 对象
        SM2 sm2 = SmUtil.sm2();
        // 这里会自动生成对应的随机秘钥对 , 注意！ 这里一定要强转，才能得到对应有效的秘钥信息
        String privateKey = sm2.getPrivateKeyBase64();
        // 这里公钥不压缩 公钥的第一个字节用于表示是否压缩 可以不要
        String publicKey = sm2.getPublicKeyBase64();
        System.out.println("--------private key--------");
        System.out.println(privateKey);
        System.out.println("--------public key---------");
        System.out.println(publicKey);
    }
    //SM4秘钥生成工具
    public static void sm4KeyGen() {
        // 创建sm4 对象
        SM4 sm4 = SmUtil.sm4();
        // 这里会自动生成对应的秘钥
        SecretKey secretKey = sm4.getSecretKey();
        System.out.println("--------sm4 key--------");
        System.out.println(HexUtil.encodeHexStr(secretKey.getEncoded()).toUpperCase());
    }
    //********************通过私钥签名********************
    public static String sign(String privateKey, String appId, String dataStr) throws Exception {
        PrivateKey pk = privKeySM2FromBase64Str(privateKey);
        return signSM3SM2RetBase64(pk, appId, dataStr.getBytes(StandardCharsets.UTF_8));
    }
    //********************通过公钥验签********************
    public static boolean verifySign(String publicKey, String appId, String sign, String dataStr) throws Exception {
        PublicKey pk = pubKeySM2FromBase64Str(publicKey);
        return verifySM3SM2(pk, appId, Base64.decode(sign), dataStr.getBytes(StandardCharsets.UTF_8));
    }
    //********************SM3withSM2签名工具********************
    /**签名并BASE64编码-SM3WithSM2 */
    public static String signSM3SM2RetBase64(final PrivateKey privateKey,String certid,final byte[] data) throws Exception{
        return Base64.encode(signSM3SM2(privateKey, certid, data));
    }
    //********************SM3withSM2验签工具********************
    /** 验证签名-SM3WithSM2*/
    public static boolean verifySM3SM2(final PublicKey publicKey,String certid,final byte[] signData, final byte[] srcData) throws Exception {
        SM2ParameterSpec parameterSpec = new SM2ParameterSpec(certid.getBytes());
        Signature verifier = Signature.getInstance(ALGORITHM_SM3SM2_BCPROV, "BC");
        verifier.setParameter(parameterSpec);
        verifier.initVerify(publicKey);
        verifier.update(srcData);
        return verifier.verify(bytePlain2ByteAsn1(signData));
    }
    //********************SM4加密工具********************
    /**
     * sm4加密 加密模式：ECB 密文长度不固定，会随着被加密字符串长度的变化而变化
     * @param hexKey 16进制密钥（忽略大小写）
     * @param paramStr 待加密字符串
     * @return 返回16进制的加密字符串
     */
    public static String encryptEcb(String hexKey, String paramStr) throws Exception {
        String cipherText;
        // 16进制字符串-->byte[]
        byte[] keyData = ByteUtils.fromHexString(hexKey);
        // String-->byte[]
        byte[] srcData = paramStr.getBytes(ENCODING);
        // 加密后的数组
        byte[] cipherArray = encrypt_Ecb_Padding(keyData, srcData);
        // byte[]-->hexString
        cipherText = ByteUtils.toHexString(cipherArray);
        return cipherText;
    }

    //********************SM4解密工具********************
    /**
     * sm4解密 解密模式：采用ECB
     * @param hexKey 16进制密钥
     * @param cipherText 16进制的加密字符串（忽略大小写）
     * @return 解密后的字符串
     */
    public static String decryptEcb(String hexKey, String cipherText) throws Exception {
        // 用于接收解密后的字符串
        String decryptStr;
        // hexString-->byte[]
        byte[] keyData = ByteUtils.fromHexString(hexKey);
        // hexString-->byte[]
        byte[] cipherData = ByteUtils.fromHexString(cipherText);
        // 解密
        byte[] srcData = decrypt_Ecb_Padding(keyData, cipherData);
        // byte[]-->String
        decryptStr = new String(srcData, ENCODING);
        return decryptStr;
    }


    /**签名-SM3WithSM2 */
    private static byte[] signSM3SM2(final PrivateKey privateKey,String certid,final byte[] data) throws Exception{
        SM2ParameterSpec parameterSpec = new SM2ParameterSpec(certid.getBytes());
        Signature signer = Signature.getInstance(ALGORITHM_SM3SM2_BCPROV, "BC");
        signer.setParameter(parameterSpec);
        signer.initSign(privateKey, new SecureRandom());
        signer.update(data);
        return byteAsn12BytePlain(signer.sign());
    }


    /**从字符串读取私钥-目前支持PKCS8(keystr为BASE64格式)*/
    private static PrivateKey privKeySM2FromBase64Str(String keystr) throws Exception {
        KeyFactory keyFactory = KeyFactory.getInstance("EC");
        return keyFactory.generatePrivate(new PKCS8EncodedKeySpec(Base64.decode(keystr)));
    }

    /**从字符串读取RSA公钥(keystr为BASE64格式)*/
    private static PublicKey pubKeySM2FromBase64Str(String keystr) throws Exception {
        KeyFactory keyFactory = KeyFactory.getInstance("EC");
        return keyFactory.generatePublic(new X509EncodedKeySpec(Base64.decode(keystr)));
    }

    /**
     * 将普通字节数组转换为ASN1字节数组 适用于SM3withSM2验签时验签明文转换
     */
    private static byte[] bytePlain2ByteAsn1(byte[] data) {
        if (data.length != SM3withSM2_RS_LEN * 2) throw new RuntimeException("err data. ");
        BigInteger r = new BigInteger(1, Arrays.copyOfRange(data, 0, SM3withSM2_RS_LEN));
        BigInteger s = new BigInteger(1, Arrays.copyOfRange(data, SM3withSM2_RS_LEN, SM3withSM2_RS_LEN * 2));
        ASN1EncodableVector v = new ASN1EncodableVector();
        v.add(new ASN1Integer(r));
        v.add(new ASN1Integer(s));
        try {
            return new DERSequence(v).getEncoded("DER");
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
    /**
     * 将ASN1字节数组转换为普通字节数组 适用于SM3withSM2签名时签名结果转换
     */
    private static byte[] byteAsn12BytePlain(byte[] dataAsn1) {
        ASN1Sequence seq = ASN1Sequence.getInstance(dataAsn1);
        byte[] r = bigIntToFixexLengthBytes(ASN1Integer.getInstance(seq.getObjectAt(0)).getValue());
        byte[] s = bigIntToFixexLengthBytes(ASN1Integer.getInstance(seq.getObjectAt(1)).getValue());
        byte[] result = new byte[SM3withSM2_RS_LEN * 2];
        System.arraycopy(r, 0, result, 0, r.length);
        System.arraycopy(s, 0, result, SM3withSM2_RS_LEN, s.length);
        return result;
    }

    private static byte[] bigIntToFixexLengthBytes(BigInteger rOrS) {
        byte[] rs = rOrS.toByteArray();
        if (rs.length == SM3withSM2_RS_LEN) return rs;
        else if (rs.length == SM3withSM2_RS_LEN + 1 && rs[0] == 0)
            return Arrays.copyOfRange(rs, 1, SM3withSM2_RS_LEN + 1);
        else if (rs.length < SM3withSM2_RS_LEN) {
            byte[] result = new byte[SM3withSM2_RS_LEN];
            Arrays.fill(result, (byte) 0);
            System.arraycopy(rs, 0, result, SM3withSM2_RS_LEN - rs.length, rs.length);
            return result;
        } else {
            throw new RuntimeException("err rs: " + Hex.toHexString(rs));
        }
    }

    /**
     * 生成ECB暗号 ECB模式（电子密码本模式：Electronic codebook）
     * @param mode 模式
     * @param key 秘钥
     */
    private static Cipher generateEcbCipher(int mode, byte[] key) throws Exception {
        Cipher cipher = Cipher.getInstance(SysEncryptionUtil.ALGORITHM_NAME_ECB_PADDING, BouncyCastleProvider.PROVIDER_NAME);
        Key sm4Key = new SecretKeySpec(key, ALGORITHM_NAME);
        cipher.init(mode, sm4Key);
        return cipher;
    }

    /**
     * 自动生成密钥
     */
    public static byte[] generateKey() throws Exception {
        return generateKey(DEFAULT_KEY_SIZE);
    }

    /**
     * 系统产生秘钥
     * @param keySize 秘钥长度
     */
    public static byte[] generateKey(int keySize) throws Exception {
        KeyGenerator kg = KeyGenerator.getInstance(ALGORITHM_NAME, BouncyCastleProvider.PROVIDER_NAME);
        kg.init(keySize, new SecureRandom());
        return kg.generateKey().getEncoded();
    }

    /**
     * 加密模式之Ecb
     */
    public static byte[] encrypt_Ecb_Padding(byte[] key, byte[] data) throws Exception {
        Cipher cipher = generateEcbCipher(Cipher.ENCRYPT_MODE, key);//声称Ecb暗号,通过第二个参数判断加密还是解密
        return cipher.doFinal(data);
    }



    /**
     * 解密
     */
    public static byte[] decrypt_Ecb_Padding(byte[] key, byte[] cipherText) throws Exception {
        Cipher cipher = generateEcbCipher(Cipher.DECRYPT_MODE, key);//生成Ecb暗号,通过第二个参数判断加密还是解密
        return cipher.doFinal(cipherText);
    }

    /**
     * 校验加密前后的字符串是否为同一数据
     * @param hexKey 16进制密钥（忽略大小写）
     * @param cipherText 16进制加密后的字符串
     * @param paramStr 加密前的字符串
     * @return 是否为同一数据
     */
    public static boolean verifyEcb(String hexKey, String cipherText, String paramStr) throws Exception {
        // 用于接收校验结果
        boolean flag;
        // hexString-->byte[]
        byte[] keyData = ByteUtils.fromHexString(hexKey);
        // 将16进制字符串转换成数组
        byte[] cipherData = ByteUtils.fromHexString(cipherText);
        // 解密
        byte[] decryptData = decrypt_Ecb_Padding(keyData, cipherData);
        // 将原字符串转换成byte[]
        byte[] srcData = paramStr.getBytes(ENCODING);
        // 判断2个数组是否一致
        flag = Arrays.equals(decryptData, srcData);
        return flag;
    }

    public static TreeMap<String, Object> sortField(Map<String, Object> map) {
        TreeMap<String, Object> reJo = new TreeMap<>(map);
        for (Map.Entry<String, Object> entry : map.entrySet()) {
            String key = entry.getKey();
            Object value = entry.getValue();
            if (value instanceof Map) {
                reJo.put(key, sortField((Map<String, Object>) value));
            }
        }
        return reJo;
    }
    public static void main(String[] args) throws Exception {
        sm2KeyGen();
        sm4KeyGen();
        //业务端被分配的appid,也是签名的certid
        String appid = "00000156";
        //业务端sm2私钥,发送请求时生成签名（业务端保留）
        String cusPrivateKey = "MIGTAgEAMBMGByqGSM49AgEGCCqBHM9VAYItBHkwdwIBAQQgjj4Rk+b0YjwO+UwXofnHf4bK+kaaY5Btkd8nMP2VimmgCgYIKoEcz1UBgi2hRANCAAQqlALW4qGC3bP1x3wo5QsKxaCMEZJ2ODTTwOQ+d8UGU7GoK/y/WMBQWf5upMnFU06p5FxGooXYYoBtldgm03hq";
        //业务端sm2公钥，系统收到请求时验签使用（上传给系统）
        String cusPubKey = "MFkwEwYHKoZIzj0CAQYIKoEcz1UBgi0DQgAEKpQC1uKhgt2z9cd8KOULCsWgjBGSdjg008DkPnfFBlOxqCv8v1jAUFn+bqTJxVNOqeRcRqKF2GKAbZXYJtN4ag==";
        //系统端sm2私钥，返回业务端数据时签名使用（系统保留）
        String sysPriKey = "MIGTAgEAMBMGByqGSM49AgEGCCqBHM9VAYItBHkwdwIBAQQg2kxXgQ/5ofE0+eG3wK8ih37LxVUlj4eopCKonTeDBUCgCgYIKoEcz1UBgi2hRANCAATrof2nzCdBqCdBzCSuVnfF+gUnONNKokUjOAIxHRKEHFZ4h339SlBalrani9QbHAEr5m8EYnFJw3V06Qm2OTnd";
        //系统端sm2公钥，业务端接收时验签使用（下发给业务端）
        String sysPubKey = "MFkwEwYHKoZIzj0CAQYIKoEcz1UBgi0DQgAE66H9p8wnQagnQcwkrlZ3xfoFJzjTSqJFIzgCMR0ShBxWeId9/UpQWpa2p4vUGxwBK+ZvBGJxScN1dOkJtjk53Q==";
        //待签名串生成
        JSONObject data = new JSONObject();
        data.set("appId", "111");
        data.set("orderId", 123);
        data.set("orderNo", "2024001");
        data.set("mobile", "18211962110");
        data.set("name", "张三");
        JSONObject goods = new JSONObject();
        goods.set("goodId", "001");
        goods.set("goodsNum", 2);
        goods.set("goodsName", "采煤机");
        data.set("goods", goods);
        System.out.println("排序前" + JSONUtil.toJsonStr(data));
        TreeMap<String, Object> sortData = sortField(data);
        System.out.println("排序后" + JSONUtil.toJsonStr(sortData));
        //====================== 签名验签 ======================
        String blankStr = "请求待签名数据";
        PrivateKey privkey = privKeySM2FromBase64Str(cusPrivateKey);
        //业务端签名
        String sign = signSM3SM2RetBase64(privkey, appid, blankStr.getBytes(StandardCharsets.UTF_8));//签名
        System.out.println("业务端签名：" + sign);
        //系统验签
        boolean ok = verifySM3SM2(pubKeySM2FromBase64Str(cusPubKey), appid, Base64.decode(sign), blankStr.getBytes(StandardCharsets.UTF_8));
        System.out.println("系统验签结果" + ok);

        String rspBlankStr = "返回待验签数据";//通联返回的明文
        //系统签名
        String sysSign = signSM3SM2RetBase64(privKeySM2FromBase64Str(sysPriKey), appid, rspBlankStr.getBytes(StandardCharsets.UTF_8));
        System.out.println("系统签名：" + sysSign);

        PublicKey publicKey = pubKeySM2FromBase64Str(sysPubKey);
        //业务端验签
        boolean isOk = verifySM3SM2(publicKey, appid, Base64.decode(sysSign), rspBlankStr.getBytes(StandardCharsets.UTF_8));
        System.out.println("业务端验签结果:"+isOk);

        String signData = "签名验签测试";
        String sign1 = sign(cusPrivateKey, appid, signData);
        boolean ok2 = verifySign(cusPubKey, appid, sign1, signData);
        System.out.println("验签结果：" + ok2);

        System.out.println("另一种生成方式" + HexUtil.encodeHexStr(generateKey()));
        //SM4对称加解密
        String plainStr = "我是一个明文";
        String sm4Key = "CEA6BFD1609181BC380B453A723F0D19";
        String cipher = encryptEcb(sm4Key,plainStr);
        String result = decryptEcb(sm4Key, cipher);
        System.out.println(cipher);
        System.out.println(result);

    }


}
